package com.youbug.mall.ware_wms.feign.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.youbug.common.to.SkuHasStockTo;
import com.youbug.common.vo.FareVo;
import com.youbug.common.vo.R;
import com.youbug.mall.order_oms.feign.IOrderWareFeignService;
import com.youbug.mall.order_oms.vo.WareSkuLockVo;
import com.youbug.mall.product_pms.feign.IWareFeignService;
import com.youbug.mall.ware_wms.entity.WmsWareSku;
import com.youbug.mall.ware_wms.service.IWmsWareInfoService;
import com.youbug.mall.ware_wms.service.IWmsWareSkuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class WareFeignServiceImpl implements IWareFeignService, IOrderWareFeignService {

    @Autowired
    private IWmsWareSkuService wareSkuService;

    @Autowired
    private IWmsWareInfoService wmsWareInfoService;

    @Override
    public List<SkuHasStockTo> getSkuHasStock(List<Long> skuIds) {

        List<WmsWareSku> wareSkus = wareSkuService.list(new QueryWrapper<WmsWareSku>().in("sku_id", skuIds));

        Map<Long, Long> tempStock = new HashMap<>();

        wareSkus.forEach(s->{

            Long stock = tempStock.get(s.getSkuId());
            if(stock!=null){
                stock = stock + (s.getStock() - s.getStockLocked());
                tempStock.put(s.getSkuId(), stock);
            }else{
                tempStock.put(s.getSkuId(), (long) (s.getStock() - s.getStockLocked()));
            }
        });

        List<SkuHasStockTo> voList = skuIds.stream().map(skuId -> {
            SkuHasStockTo vo = new SkuHasStockTo();
            vo.setSkuId(skuId);
            Long stock = tempStock.get(vo.getSkuId());
            if (stock != null && stock > 0) {
                vo.setHasStock(true);
            } else {
                vo.setHasStock(false);
            }
            return vo;
        }).collect(Collectors.toList());

        return voList;
    }

    @Override
    public FareVo getFare(Long addrId) {

        return wmsWareInfoService.getFare(addrId);
    }

    @Override
    public R<Boolean> orderLockStock(WareSkuLockVo lockVo) {

        return wareSkuService.orderLockStock(lockVo);
    }
}
